package com.fenyin.samples.study.jdk.nio.channels.file;

import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.IntBuffer;
import java.nio.channels.FileChannel;
import java.nio.channels.FileLock;
import java.util.Random;

/**
 * 使用共享锁读文件
 *@Author:fengzhichao  
 *@Since:2012-12-14  
 *@Version:1.1.0
 */
public class FileSharedReader {
	
	private static final int SIZEOF_INT = 4;
	private static final int INDEX_START = 0;
	private static final int INDEX_COUNT = 10;
	private static final int INDEX_SIZE = INDEX_COUNT * SIZEOF_INT;
	
	private ByteBuffer buffer = ByteBuffer.allocate(INDEX_SIZE);
	
	private IntBuffer indexBuffer = buffer.asIntBuffer();
	
	private Random rand = new Random();
	
	private static final String filename="temp.txt";

	// ----------------------------------------------------------------
	private int lastLineLen = 0;
	
	public static void main(String[] argv) throws Exception{
		
		RandomAccessFile file = new RandomAccessFile(filename, "r");
		FileChannel fileChannel = file.getChannel();
		FileSharedReader reader = new FileSharedReader();
		reader.doQueries(fileChannel);
	}

	// ----------------------------------------------------------------
	// Simulate a series of read-only queries while
	// holding a shared lock on the index area
	void doQueries(FileChannel fileChannel) throws Exception {
		while (true) {
			println("trying for shared lock...");
			FileLock lock = fileChannel.lock(INDEX_START, INDEX_SIZE, true);
			try{
				int reps = rand.nextInt(60) + 20;
				for (int i = 0; i < reps; i++) {
					int n = rand.nextInt(INDEX_COUNT);
					int position = INDEX_START + (n * SIZEOF_INT);
					buffer.clear();
					fileChannel.read(buffer, position);
					int value = indexBuffer.get(n);
					println("Index entry " + n + "=" + value);
					// Pretend to be doing some work
					Thread.sleep(100);
				}
			}catch(Throwable th){
				th.printStackTrace();
			}finally{
				lock.release();
				println("<sleeping>");
				Thread.sleep(rand.nextInt(3000) + 500);
			}
		}
	}

	// Specialized println that repaints the current line
	private void println(String msg) {
		System.out.print("\r ");
		System.out.print(msg);
		for (int i = msg.length(); i < lastLineLen; i++) {
			System.out.print(" ");
		}
		System.out.print("\r");
		System.out.flush();
		lastLineLen = msg.length();
	}
}